package ele.utils;

import app.nbdevices.utils.ConvertUtil;

import ele.entity.EleCycleReport;
import ele.modle.codecModle.EleDataField;
import ele.modle.codecModle.EleReport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;

/**
 * 电表解释器
 */

public class EleExplain {
    /**
     * 解释周期上报数据
     * @param eleReport
     * @return
     */
    public static EleCycleReport exEleCycle(EleReport eleReport){
        EleCycleReport eleCycleReport=new EleCycleReport();
        Long time=LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        eleCycleReport.setAddrId(explainAddr(eleReport.getAddressField()));
        eleCycleReport.setEleCycleCode((int)eleReport.getControlCode());

        ArrayList<EleDataField> eleDataFields=eleReport.getDataFields();
        eleCycleReport.setEleData(explainRead(eleDataFields.get(0)));
        eleCycleReport.setEleCycleReportTime(explainTime(eleDataFields.get(1)));
        eleCycleReport.setEleStatus(explainStatus(eleDataFields.get(2)));
        eleCycleReport.setReportTime(time);
        int[] res=getDayMonYear(time);
        eleCycleReport.setDay(res[0]);
        eleCycleReport.setMon(res[1]);
        eleCycleReport.setYear(res[2]);
        return eleCycleReport;
    }
    /**
     * 转换表号
     */
    private static String explainAddr(byte[] a){
//        StringBuffer addrId=new StringBuffer();
//        for(int i=a.length-1;i>=0;i--){
//            addrId.append(ConvertUtil.byteToString(a[i]));
//        }
//        return addrId.toString();
        return ConvertUtil.getBase64Codec().encodeToString(a);
    }
    /**
     * 解释电表读数
     * @param data
     * @return
     */
    private static double explainRead(EleDataField data){
        if(!compareByteArray(DataID.READ,data.getDataId())){
            return -10.0;
        }
        StringBuffer tempReading=new StringBuffer();
        for(int i=data.getData().length-1;i>=0;i--){
            String s = Integer.toHexString(data.getData()[i] & 0xff);
            //避免丢失0
            if(s.length()==1){
                tempReading.append("0");
            }
            tempReading.append(s);
            if(i==1){
                tempReading.append(".");
            }
        }
        System.out.println(tempReading);
        return Double.parseDouble(tempReading.toString());
    }

    public static void main(String[] args) {
       // String s = LocalDateTime.parse(String.valueOf(1586510882l), ConvertUtil.getFormatter()).toString();
        Instant instant = Instant.ofEpochMilli(1586510882000l);
        LocalDateTime time = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        String format = time.format(ConvertUtil.getFormatter());
        System.out.println(format);
        //   System.out.println(s);
//        byte[] bs={0x57,0x01,0x00};
//        StringBuffer tempReading=new StringBuffer();
//        for(int i=bs.length-1;i>=0;i--){
//            tempReading.append(Integer.toHexString(bs[i]&0xff));
//            if(i==1){
//                tempReading.append(".");
//            }
//        }


  //      System.out.println(Double.parseDouble(tempReading.toString()));

    }
    /**
     * 解释时间
     * @param data
     * @return
     */
    private static Long explainTime(EleDataField data){
        //比较数据标识
        if(!compareByteArray(DataID.TIME,data.getDataId())){
            return null;
        }
        byte[] a=data.getData();
        int year=Integer.parseInt(ConvertUtil.byteToString(a[6]))+2000;
        int mounth=Integer.parseInt(ConvertUtil.byteToString(a[5]));
        int day=Integer.parseInt(ConvertUtil.byteToString(a[4]));
        int hour=Integer.parseInt(ConvertUtil.byteToString(a[2]));
        int minute=Integer.parseInt(ConvertUtil.byteToString(a[1]));
        int second=Integer.parseInt(ConvertUtil.byteToString(a[0]));
        LocalDateTime time= LocalDateTime.of(year,mounth,day,hour,minute,second);
        return time.toEpochSecond(ZoneOffset.of("+8"));
    }

    /**
     * 解释状态码
     * @param data
     * @return
     */
    private static String explainStatus(EleDataField data){
        if(!compareByteArray(data.getDataId(),DataID.STATUS)){
            return null;
        }
        return ConvertUtil.getBase64Codec().encodeAsString(data.getData());
    }

    /**
     * 比较byte数组
     * @param b1
     * @param b2
     * @return
     */
    private static boolean compareByteArray(byte[] b1,byte[] b2){
        if(b1==null||b2==null||b1.length==0||b2.length==0||b1.length!=b2.length){
            return false;
        }
        for(int i=0;i<b1.length;i++){
            if(b1[i]!=b2[i]){
                return false;
            }
        }
        return true;
    }

    public static int[] getDayMonYear(Long time){
        LocalDateTime time1 = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.ofHours(8));
        String dd=time1.format(ConvertUtil.getFormatter());
        int res[]=new int[3];
        res[0]=Integer.parseInt(dd);
        res[1]=Integer.parseInt(dd.substring(0,6));
        res[2]=Integer.parseInt(dd.substring(0,4));
        return res;
    }

//    public static int[] getDayMonYear(Long time){
//        final int[] days={31,59,90,120,151,181,212,243,273,304,334,365};
//        final Long nd = 24l * 60l * 60l;
//        int[] res=new int[3];
//        Long t=(time%nd)/nd;
//        int day=new Long((time-time%nd)/nd).intValue()+1;
//        res[0]=day;
//        day=day-(365*3+1);
//        int nowDay=day%(365*4+1);
//
//        int year=1973+day/(365*4+1)*4+nowDay/365;
//        res[2]=year;
//        int nowYearDay=nowDay%365;
//        if(nowYearDay<=31){
//            res[1]=1;
//        }else  if(year % 4== 0 && year%100!=0||year%400==0){
//            for (int i = 1; i < days.length; i++) {
//                if (nowYearDay <= (days[i]+1)) {
//                    res[1]=i+1;
//                    break;
//                }
//            }
//        }else {
//            for (int i = 1; i < days.length; i++) {
//                if (nowYearDay <= days[i]) {
//                    res[1]=i+1;
//                }
//            }
//        }
//        return res;
//    }
//    public static void main(String[] args) {
//        String t="2019-07-16 20:18:53";
//        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = null;
//        try {
//            date = format.parse(t);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        //日期转时间戳（毫秒）
//        long times=date.getTime()/1000;
//
//        System.out.println(times);
//    }
}
